# -*- coding: utf-8 -*-

'''
Description: 
'''
# -*- coding: utf-8 -*-

"""
Description:
"""
import time
import requests
from functools import wraps
from website.elabscience.utils import *

base_url = "https://www.elabscience.cn"

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
}

def retry_on_failure(max_retries=3, delay=1):
    """
    请求重试装饰器
    :param max_retries: 最大重试次数
    :param delay: 重试间隔时间（秒）
    """

    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            retries = 0
            while retries < max_retries:
                try:
                    response = func(*args, **kwargs)
                    # 检查响应状态码
                    if response.status_code == 200:
                        return response
                    print(
                        f"请求失败，状态码: {response.status_code}，第 {retries + 1} 次重试..."
                    )
                except requests.RequestException as e:
                    print(f"请求异常: {str(e)}，第 {retries + 1} 次重试...")

                retries += 1
                if retries < max_retries:
                    time.sleep(delay * retries)  # 指数退避
            raise Exception(f"达到最大重试次数 {max_retries}，请求失败")

        return wrapper

    return decorator


@retry_on_failure(max_retries=5, delay=10)
def get_request(url, headers):
    return requests.get(url, headers=headers)

def search_product(keyword: str):
    """商品搜索

    Args:
        keyword (str): 商品货号

    Returns:
        _type_: _description_
    """
    url = f"{base_url}/search?keywords={keyword}"
    respon = requests.get(url, headers=headers)
    return respon.text
    # links = extract_product_links(respon.text)
    # return links


def search_product_by_code(procode: str):
    """商品搜索

    Args:
        procode (str): 商品货号
    """
    url = f"{base_url}/search?keywords={procode}"
    respon = get_request(url, headers=headers)
    for item in extract_search_result(respon.text):
        if item["code"] == procode:
            return item
        else:
            return None


def get_product_detail(link: str):
    """获取商品详情

    Args:
        link (str): 商品链接
    """
    respon = requests.get(link, headers=headers)

    return extract_product_detail(respon.text)
